package com.shanling.shanlingcontroller.ui.activity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.chipsguide.lib.bluetooth.entities.BluetoothDeviceMusicSongEntity;
import com.chipsguide.lib.bluetooth.managers.BluetoothDeviceManager;
import com.chipsguide.lib.bluetooth.managers.BluetoothDeviceMusicManager;
import com.shanling.shanlingcontroller.CustomApplication;
import com.shanling.shanlingcontroller.R;
import com.shanling.shanlingcontroller.adapter.MusicPlayFragmentPagerAdapter;
import com.shanling.shanlingcontroller.base.BaseAppCompatActivity;
import com.shanling.shanlingcontroller.base.BaseLazyFragment;
import com.shanling.shanlingcontroller.bean.Constants;
import com.shanling.shanlingcontroller.bean.EventCenter;
import com.shanling.shanlingcontroller.bean.Music;
import com.shanling.shanlingcontroller.manager.DeviceMusicManager;
import com.shanling.shanlingcontroller.music.event.MetaChangedEvent;
import com.shanling.shanlingcontroller.music.event.StatusChangedEvent;
import com.shanling.shanlingcontroller.music.player.MusicPlayerService;
import com.shanling.shanlingcontroller.music.player.PlayManager;
import com.shanling.shanlingcontroller.music.player.playback.PlayProgressListener;
import com.shanling.shanlingcontroller.ui.fragment.MusicCoverFragment;
import com.shanling.shanlingcontroller.ui.fragment.MusicInformationFragment;
import com.shanling.shanlingcontroller.utils.FormatUtil;
import com.shanling.shanlingcontroller.utils.ToastUtils;
import com.shanling.shanlingcontroller.utils.UIUtils;
import com.shanling.shanlingcontroller.view.MusicListPopup;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MusicPlayActivity extends BaseAppCompatActivity implements PlayProgressListener {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    @BindView(R.id.ll_indicate)
    LinearLayout llIndicate;
    @BindView(R.id.tv_song_name)
    TextView tvSongName;
    @BindView(R.id.tv_singer)
    TextView tvSinger;
    @BindView(R.id.tv_startTime)
    TextView tvStartTime;
    @BindView(R.id.musicTimeSb)
    SeekBar musicTimeSb;
    @BindView(R.id.tv_endTime)
    TextView tvEndTime;
    @BindView(R.id.iv_playmode)
    ImageView ivPlaymode;
    @BindView(R.id.iv_last)
    ImageView ivLast;
    @BindView(R.id.iv_play)
    ImageView ivPlay;
    @BindView(R.id.lv_next)
    ImageView lvNext;
    @BindView(R.id.iv_list)
    ImageView ivList;
    private LinearLayout.LayoutParams dotParams;
    private List<BaseLazyFragment> fragments=new ArrayList<>();
    private Music music;
    private MusicListPopup musicListPopup;

    @Override
    protected void getBundleExtras(Bundle extras) {
        music=extras.getParcelable("music");
    }
    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_music_play;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CustomApplication.getInstance().getBluetoothDeviceManager().setMode(BluetoothDeviceManager.Mode.A2DP);
    }

    @Override
    protected void initViewsAndEvents() {
        MusicCoverFragment musicCoverFragment=new MusicCoverFragment();
       Bundle bundle= new Bundle();
        bundle.putParcelable("music",music);
        musicCoverFragment.setArguments(bundle);
        fragments.add(musicCoverFragment);
        fragments.add(new MusicInformationFragment());
        MusicPlayFragmentPagerAdapter adapter=new MusicPlayFragmentPagerAdapter(getSupportFragmentManager(),fragments);
        viewPager.setAdapter(adapter);
        initViewListener();
        initDotViews();
        updatePlayMode();
        updatePlayView();
        setSinger(PlayManager.getPlayingMusic());
        musicListPopup=new MusicListPopup(this);
    }

    private void setSinger(Music music) {
        tvSongName.setSelected(true);
        if(music==null){
            tvSinger.setText(getString(R.string.unknown));
            tvSongName.setText(getString(R.string.unknown));
        }else {
            tvSinger.setText(music.getArtist());
            tvSongName.setText(music.getTitle());
        }
    }
    private void updatePlayView() {
        if(PlayManager.isPlaying()){
            ivPlay.setImageResource(R.drawable.player_btn_pause);
        }else {
            ivPlay.setImageResource(R.drawable.player_btn_play);
        }
    }

    private void initDotViews() {
        dotParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dotParams.leftMargin = 5;
        dotParams.rightMargin = 5;
        if (llIndicate.getChildCount() > 0) {
            return;
        }
        ImageView dotImage;
        for (int i = 0; i < fragments.size(); i++) {
            dotImage = new ImageView(mContext);
            if (i == 0) {
                dotImage.setImageResource(R.drawable.point_select);
            } else {
                dotImage.setImageResource(R.drawable.point_normal);
            }
            dotImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
            llIndicate.addView(dotImage, dotParams);
        }
    }
    private void initViewListener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                ImageView imageView;
                for (int i = 0; i < llIndicate.getChildCount(); i++) {
                    imageView = (ImageView) llIndicate.getChildAt(i);    //获取指定位置的子控件
                    if (i == position) {
                        imageView.setImageResource(R.drawable.point_select);
                    } else {
                        imageView.setImageResource(R.drawable.point_normal);
                    }
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        musicTimeSb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                PlayManager.seekTo(seekBar.getProgress());
            }
        });
    }

    private void updatePlayMode() {
        UIUtils.INSTANCE.updatePlayMode(ivPlaymode, false);
    }

    @Override
    protected void initData() {
        MusicPlayerService.addProgressListener(this);
    }
    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void onEventComing(EventCenter eventCenter) {
        switch (eventCenter.getEventCode()) {
            case  Constants.STATUSCHANGEEVENT:
                StatusChangedEvent statusChangedEvent= (StatusChangedEvent) eventCenter.getData();
                updatePlayView();
                break;
            case  Constants.METACHANGE:
                MetaChangedEvent eventCenterData = (MetaChangedEvent) eventCenter.getData();
                setSinger(eventCenterData.getMusic());
                break;
        }
    }
    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }
    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @OnClick({R.id.iv_back, R.id.iv_playmode, R.id.iv_last, R.id.iv_play, R.id.lv_next, R.id.iv_list})
    public void onViewClicked(View view) {
        if (UIUtils.INSTANCE.isFastClick()) return;
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_playmode:
                UIUtils.INSTANCE.updatePlayMode(ivPlaymode, true);
                break;
            case R.id.iv_last:
                PlayManager.prev();
                break;
            case R.id.iv_play:
                PlayManager.playPause();
                break;
            case R.id.lv_next:
                PlayManager.next();
                break;
            case R.id.iv_list:
                List<Music> playList = PlayManager.getPlayList();
                musicListPopup.show(playList,ivList);
                break;
        }
    }
    @Override
    public void onProgressUpdate(long position, long duration) {
        if(isOnResume){
            musicTimeSb.setMax((int) duration);
            musicTimeSb.setProgress((int)position);
            tvStartTime.setText(FormatUtil.INSTANCE.formatTime(position));
            tvEndTime.setText(FormatUtil.INSTANCE.formatTime(duration));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MusicPlayerService.removeProgressListener(this);
    }


}
